import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from 'axios'

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    age: 22,
    name: 'waterking',
    like: 'money',
    game: ['cod', 'monsterHuner', 'pokemon'],
    money: 0,
    async: false,
  },
  reducers: {
    addMoney: state => {
      console.log('money lcik');
      state.money += 10
    },
    updateUserInfo: (state, action) => {
      console.warn(action);
      state[action.payload.key] = action.payload.value
    },
    asyncChange: (state, action) => {
      state.async = !state.async
    },
  }
})

// 1.发出异步请求
export const getRequest = createAsyncThunk(
  "fetch/homemultidata",
  async (extraInfo, { dispatch }) => {
    // 1.发送网络请求获取数据
    const res = await axios.get("http://123.207.32.32:8000/home/multidata")
    // 2.从网络请求结果中取出数据
    console.log(res);

    // 3.执行dispatch, 派发action
    // dispatch(changeBanners(banners))
    // dispatch(changeRecommends(recommends))
  }
)


// 2 异步操作并修改state
export const changeAsync = (payload) => {
  return async (dispatch, getState) => {
    setTimeout(() => {
      dispatch(asyncChange())
    }, 2000);
  }
}

export default userSlice.reducer

export const { addMoney, updateUserInfo, asyncChange } = userSlice.actions
